package org.openkanban.server.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openkanban.server.interceptor.annotation.SecurityInterception;
import org.openkanban.server.session.SessionAttributeHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Checks if the user is authenticated.
 */
@Interceptor
@SecurityInterception
@Component
public class SecurityInterceptor {

    @Autowired
    private SessionAttributeHelper sessionAttributes;

    /**
     * Method will be called on every other method that is annotated with @SecurityInterception
     * and only proceeds the method call if the user is authenticated. Otherwise
     * it will return HTTP Status 401.
     * 
     * @param ctx
     * @return
     * @throws Exception
     */
    @AroundInvoke
    public Object validateSession(InvocationContext ctx) throws Exception {
	Object[] params = ctx.getParameters();

	HttpServletRequest req = null;
	HttpServletResponse resp = null;

	for (Object param : params) {
	    if (param instanceof HttpServletRequest) {
		req = (HttpServletRequest) param;
	    } else if (param instanceof HttpServletResponse) {
		resp = (HttpServletResponse) param;
	    }
	}

	if (req == null || sessionAttributes.getUserId(req) == null) {
	    if (resp != null) {
		resp.setStatus(401);
	    }

	    return null;
	}

	return ctx.proceed();
    }

    public void setSessionAttributes(SessionAttributeHelper sessionAttributes) {
	this.sessionAttributes = sessionAttributes;
    }

}
